//
//  UserViewController.m
//  B-72K
//
//  Created by sos on 16/3/7.
//  Copyright © 2016年 sos. All rights reserved.
//

#import "UserViewController.h"
#import "WeatherViewController.h"

#import "AboutUserViewController.h"


#import "ReadRecordViewController.h"
#import "SetUpViewController.h"
#import "AllPrefixHeader.pch"
#import "CollectViewController.h"

#import "UserFeedBackViewController.h"


#import <TencentOpenAPI/TencentOAuth.h>
#import <UIImageView+WebCache.h>
@interface UserViewController ()<UITableViewDataSource,UITableViewDelegate,TencentSessionDelegate,TencentLoginDelegate>
@property (nonatomic,retain) UITableView *userTable;


@property (nonatomic, strong)TencentOAuth *tencentOAuth;/**< qq */
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //导航栏的隐藏
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationItem.title = @"我的";
    // Do any additional setup after loading the view.
    
    //创建
    self.userTable = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    //背景颜色
//    _userTable.backgroundColor = [UIColor whiteColor];
    [_userTable NightWithType:UIViewColorTypeNormal];
    //签代理
    
    _userTable.delegate = self;
    _userTable.dataSource = self;
    
    //注册
    [_userTable registerClass:[UITableViewCell class] forCellReuseIdentifier:@"user"];
    
    _userTable.separatorStyle = NO;
    
    //添加父视图
    self.userTable.contentInset = UIEdgeInsetsMake(180*H, 0, 0, 0);

    [self.view addSubview:self.userTable];
    
    //创建tableview 的头视图
    //zoomIV
    
    //创建tableview 的头视图
    UIImageView *header = [[UIImageView alloc]initWithFrame:CGRectMake(0, -180*H, WIDTH, 180*H)];
    header.userInteractionEnabled = YES;
    header.tag = 99999;
    header.image = [UIImage imageNamed:@"denglu.jpg"];
    header.contentMode = UIViewContentModeScaleAspectFill;
//    header.backgroundColor = [UIColor whiteColor];
    [header NightWithType:UIViewColorTypeNormal];
    
//    _userTable.tableHeaderView = header;
    
    [_userTable addSubview:header];
    
    //创建设置按钮
    UIButton *setButton = [UIButton buttonWithType:UIButtonTypeCustom];
    setButton.frame = CGRectMake(self.view.frame.size.width - 40, 20, 30, 30);
    [header addSubview:setButton];
    [setButton setImage:[UIImage imageNamed:@"shezhi"] forState:UIControlStateNormal];
    [setButton addTarget:self action:@selector(shezhiye) forControlEvents:UIControlEventTouchUpInside];
//创建头像
    UIImageView *headSculpture = [[UIImageView alloc]initWithFrame:CGRectMake(20, header.frame.size.height-150, 80, 80)];
    headSculpture.tag = 8888;
    headSculpture.image = [UIImage imageNamed:@"qqHeader.jpg"];
    headSculpture.layer.cornerRadius = 40;
//    headSculpture.backgroundColor = [UIColor yellowColor];
    [header addSubview:headSculpture];
    
    UIButton *logButton = [UIButton buttonWithType:UIButtonTypeCustom];
    logButton.tag = 7777;
//    logButton.backgroundColor = [UIColor yellowColor];
    logButton.frame = CGRectMake(40, 150, 50, 30);
    logButton.center = CGPointMake(headSculpture.center.x, headSculpture.center.y+60);
    [logButton setTitle:@"登录" forState:UIControlStateNormal];
    [logButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [logButton addTarget:self action:@selector(denglu) forControlEvents:UIControlEventTouchUpInside];
    [header addSubview:logButton];
    
    
    
}

-(void)denglu
{
    NSLog(@"asdasd");
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:@"1105258940" andDelegate:self];
    
    if (_tencentOAuth.accessToken) {
        [_tencentOAuth setAccessToken:_tencentOAuth.accessToken];
        [_tencentOAuth setOpenId:_tencentOAuth.openId];
        [_tencentOAuth setExpirationDate:_tencentOAuth.expirationDate];
        
    }else{
        NSArray* permissions = [NSArray arrayWithObjects:
                                kOPEN_PERMISSION_GET_USER_INFO,
                                kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                                kOPEN_PERMISSION_ADD_ALBUM,
                                kOPEN_PERMISSION_ADD_ONE_BLOG,
                                kOPEN_PERMISSION_ADD_SHARE,
                                kOPEN_PERMISSION_ADD_TOPIC,
                                kOPEN_PERMISSION_CHECK_PAGE_FANS,
                                kOPEN_PERMISSION_GET_INFO,
                                kOPEN_PERMISSION_GET_OTHER_INFO,
                                kOPEN_PERMISSION_LIST_ALBUM,
                                kOPEN_PERMISSION_UPLOAD_PIC,
                                kOPEN_PERMISSION_GET_VIP_INFO,
                                kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                                nil];
        
        [_tencentOAuth authorize:permissions inSafari:NO];
    }
    
    
    
}

#pragma mark - qq回调协议
- (void)getUserInfoResponse:(APIResponse*) response
{
    // 三方登陆获取的头像数据
    //    "figureurl_qq_1" = "http://q.qlogo.cn/qqapp/1105164233/877B7E00A3B8F2A5CEF1CE00E9883BAB/40";
    //    "figureurl_qq_2" = "http://q.qlogo.cn/qqapp/1105164233/877B7E00A3B8F2A5CEF1CE00E9883BAB/100";
    NSLog(@"%@",response.jsonResponse);//打印用户信息
    NSLog(@"%@",[response.jsonResponse objectForKey:@"nickname"]);//打印用户昵称
    
    NSString *nameString = [response.jsonResponse objectForKey:@"nickname"];
    NSString *imageString = [NSString stringWithFormat:@"%@",[response.jsonResponse objectForKey:@"figureurl_qq_2"]];//用户头像
    // 单例保存
    [[NSUserDefaults standardUserDefaults] setObject:nameString forKey:@"name"];
    [[NSUserDefaults  standardUserDefaults] setObject:imageString forKey:@"image"];
    NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"image"]);
    
    
    UIImageView *img = [self.view viewWithTag:8888];
    [img sd_setImageWithURL:[NSURL URLWithString:[response.jsonResponse objectForKey:@"figureurl_qq_2"]]];
    
    UIButton *btn = [self.view viewWithTag:7777];
    [btn setTitle:[response.jsonResponse objectForKey:@"nickname"] forState:UIControlStateNormal];
    
    [btn sizeToFit];
    
    
   
}

#pragma mark - 点击取消键盘

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
-(void)tencentDidLogin
{
    //    _labelTitle.text = @"登录完成";
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        //        _labelAccessToken.text = _tencentOAuth.accessToken;
        NSLog(@"%@", _tencentOAuth.accessToken);
        [_tencentOAuth accessToken];
        [_tencentOAuth openId];
        [_tencentOAuth expirationDate];
        
        [_tencentOAuth getUserInfo];
        NSLog(@"登陆成功");
    }
    else
    {
        //        _labelAccessToken.text = @"登录不成功 没有获取accesstoken";
        NSLog(@"登陆不成功, 没有获取accesstoken");
    }
}

-(void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled)
    {
        //        _labelTitle.text = @"用户取消登录";
        NSLog(@"用户取消登陆");
    }
    else
    {
        //        _labelTitle.text = @"登录失败";
        NSLog(@"登陆失败");
    }
}
- (void)tencentDidNotNetWork
{
    NSLog(@"网络问题登录失败");
}
- (NSArray *)getAuthorizedPermissions:(NSArray *)permissions
                      withExtraParams:(NSDictionary *)extraParams
{
    NSLog(@"~~~~~~~%@\n %@", permissions, extraParams);
    return permissions;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //滚动就会触发
    NSLog(@"x=%.1f y=%.1f",scrollView.contentOffset.x,scrollView.contentOffset.y);
    
    /**
     *  放大原理是改变UIImageView的y坐标和高度，同时由于设置了contentMode属性，图片高度改变会使得宽度跟着改变，达到放大效果。
     */
    CGFloat y = scrollView.contentOffset.y;//根据实际选择加不加上NavigationBarHight（44、64 或者没有导航条）
    UIImageView *img = [self.view viewWithTag:99999];
    if (y < -180*H) {
        CGRect frame = img.frame;
        frame.origin.y = y;
        frame.size.height =  -y;
        img.frame = frame;
        
    }
    
}
- (void)shezhiye
{
    SetUpViewController *SetUp = [[SetUpViewController alloc] init];
    [self.navigationController pushViewController:SetUp animated:YES];
    
}
//tableview 的协议方法
//cell的个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    }else if(section == 1){
        
        return 3;
    }else{
        return 1;
    }
}
//cell的赋值
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"user" forIndexPath:indexPath];
    [cell NightWithType:UIViewColorTypeNormal];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    [cell.textLabel NightWithType:UIViewColorTypeNormal];
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        //添加辅助视图
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imageView.image = [UIImage imageNamed:@"shoucang.png"];
        cell.textLabel.text = @"我的收藏";
        return cell;
    }else if (indexPath.section == 0 && indexPath.row == 1){
        //添加辅助视图
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imageView.image = [UIImage imageNamed:@"jilu.png"];
        cell.textLabel.text = @"阅读记录";
        
    }else if (indexPath.section == 0 && indexPath.row == 2){
        //添加辅助视图
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imageView.image = [UIImage imageNamed:@"tianqi.png"];
        cell.textLabel.text = @"我的天气";

        
        
    }else if (indexPath.section == 1 && indexPath.row == 0){

    
    
    
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imageView.image = [UIImage imageNamed:@"teteshouji.png"];
        cell.textLabel.text = @"反馈信息";
        
    }else if (indexPath.section == 1 && indexPath.row == 1){
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imageView.image = [UIImage imageNamed:@"zaixiankefu.png"];
        cell.textLabel.text = @"在线客服";
        
    }else if (indexPath.section == 1 && indexPath.row == 2){
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imageView.image = [UIImage imageNamed:@"banben.png"];
        cell.textLabel.text = @"版本信息";
//    }else if (indexPath.section == 2 && indexPath.row ==0){
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//        cell.imageView.image = [UIImage imageNamed:@"erweima.png"];
//        cell.textLabel.text = @"二维码";
    }else{
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imageView.image = [UIImage imageNamed:@"guanyu.png"];
        cell.textLabel.text = @"关于";
    }
    return cell;
}
//分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        CollectViewController *collect = [[CollectViewController alloc]init];
        
        [self.navigationController pushViewController:collect animated:YES];
        
        
    }else if (indexPath.section == 0 && indexPath.row == 1){
        ReadRecordViewController *readRecord = [[ReadRecordViewController alloc]init];
    [self.navigationController pushViewController:readRecord animated:YES];
        
    }else if (indexPath.section == 0 && indexPath.row == 2){
        WeatherViewController *weather = [[WeatherViewController alloc]init];
        [self.navigationController pushViewController:weather animated:YES];
        
    }else if (indexPath.section == 1 && indexPath.row == 0){
        UserFeedBackViewController *ufbVC = [[UserFeedBackViewController alloc] init];
        [self.navigationController pushViewController:ufbVC animated:YES];
    
        
    }else if (indexPath.section == 1 && indexPath.row == 1){
        
        // 提示：不要将webView添加到self.view，如果添加会遮挡原有的视图
        // 懒加载
//        if (_webView == nil) {
//            _webView = [[UIWebView alloc] init];
//        }
//        NSLog(@"%p", _webView);
        
//            _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
//            [self.view addSubview:_webView];
        
        NSURL *url = [NSURL URLWithString:@"tel://13101668075"];
        [[UIApplication sharedApplication] openURL:url];

//        [self.view loadRequest:request];
        
    }else if (indexPath.section == 1 && indexPath.row == 2){
       

        NSString *appCurVersionNum = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        UIAlertController *aler = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"当前版本为%@",appCurVersionNum] preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:aler animated:YES completion:^{
            [self dismissViewControllerAnimated:YES completion:^{
              
               
            }];
            
            
        }];
        NSLog(@"当前应用版本号码：%@",appCurVersionNum);
    }else if (indexPath.section == 2 && indexPath.row ==0){
        
        
        AboutUserViewController *about = [[AboutUserViewController alloc]init];
        [self.navigationController pushViewController:about animated:YES];
    }else{

        
    }
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
